import logging
import numpy as np

from PyQt5.QtCore import Qt, QItemSelectionModel
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem

import errorhandle
from tools import tools


class TableOrigin(QTableWidget):
    def __init__(self, row, col):
        super(TableOrigin, self).__init__()
        self.setColumnCount(col)
        self.setRowCount(row)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        # self.customContextMenuRequested.connect(self.generate_menu)
        self.itemChanged.connect(self.item_changed)
        self.cells = [[''] * col for i in range(0, row)]

    def item_changed(self, item):
        logging.info("data change: row/col " + str(item.row()) + '/' + str(item.column()) + ' data: ' + item.text())
        if tools.is_float(item.text()):
            self.cells[item.row()][item.column()] = float(item.text())
        else:
            self.cells[item.row()][item.column()] = item.text()

    def generate_menu(self):
        pass

    def fill_sheet(self, data):
        if len(data) > self.rowCount() or len(data[0]) > self.columnCount():
            return errorhandle.DATA_OUT_OF_BOUND

        for i in range(0, len(data)):
            for j in range(0, len(data[0])):
                item = QTableWidgetItem(data[i][j].value)
                self.setItem(i, j, item)
        self.cells = list(data)

    def fill_cell(self, row, col, data):
        if row > self.rowCount() or col > self.columnCount():
            return errorhandle.DATA_OUT_OF_BOUND

        item = QTableWidgetItem(data.value)
        self.setItem(row, col, item)
        self.cells[row][col] = item

    def fill_row(self, row, data):
        if row > self.rowCount():
            return errorhandle.DATA_OUT_OF_BOUND

        for i in range(0, len(data)):
            item = QTableWidgetItem(data[i].value)
            self.setItem(row, i, item)
            self.cells[row][i] = item

    def fill_col(self, col, data):
        if col > self.columnCount():
            return errorhandle.DATA_OUT_OF_BOUND

        for i in range(0, len(data)):
            item = QTableWidgetItem(data[i].value)
            self.setItem(i, col, item)
            self.cells[i][col] = item